package com.logistics.role.service;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.logistics.account.service.AccountRoleService;
import com.logistics.role.entity.domain.RoleMenu;
import com.logistics.role.entity.model.RoleMenuSave;
import com.logistics.role.mapper.RoleMenuMapper;
import com.logistics.utils.constants.Message;
import com.logistics.utils.exception.MessageException;
import com.logistics.utils.message.Manager;
import com.logistics.utils.tool.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class RoleMenuService extends ServiceImpl<RoleMenuMapper, RoleMenu> {


    @Autowired
    private AccountRoleService accountRoleService;

    /**
     * 根据用户id查找菜单ID
     * @param userId
     * @return
     * @throws MessageException
     */
    public List<Integer> menuIdsByUserId(String userId) throws MessageException {
        List<String> roleIds = accountRoleService.roleIdsByUserId(userId);
        if(roleIds.isEmpty()){
            throw new MessageException("用户没有权限");
        }
        List<RoleMenu> list = this.list(new LambdaQueryWrapper<RoleMenu>()
                .in(RoleMenu::getRoleId, roleIds));
        return list.stream().map(e -> e.getMenuId()).distinct().collect(Collectors.toList());
    }

    /**
     * 检查菜单是否正在使用
     * @param ids
     * @throws MessageException
     */
    public void checkMenuIds(String ids) throws MessageException {
        List<RoleMenu> rows = this.list(new LambdaQueryWrapper<RoleMenu>().
                in(RoleMenu::getMenuId, StringUtils.splitToList(ids, ",")));
        if(rows.size() > 0){
            throw new MessageException(Manager.getMessage(Message.MSG1007.getCode()));
        }
    }

    /**
     * 根据角色ID查找菜单ID
     * @param roleId
     * @return
     */
    public List<String> menuIdsByRoleId(String roleId){
        return this.list(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getRoleId, roleId)).stream()
                .map(e -> e.getMenuId().toString()).collect(Collectors.toList());
    }

    /**
     * 批量保存
     * @param save
     */
    public void save(List<RoleMenuSave> save){
        this.saveBatch(save.stream().map(e -> RoleMenu.build(e)).collect(Collectors.toList()));
    }

    /**
     * 批量删除
     * @param roleIds
     */
    public void deleteByRoleIds(String roleIds){
        this.remove(new LambdaQueryWrapper<RoleMenu>()
                .in(RoleMenu::getRoleId, StringUtils.splitToList(roleIds, ",")));
    }
}
